package com.yonyou.pmclouds.repeatwork.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.billstatus.BillStatusConst;
import com.yonyou.pmclouds.basecom.bp.processor.*;
import com.yonyou.pmclouds.basecom.bp.template.SingleDeleteBpTemplate;
import com.yonyou.pmclouds.basecom.bp.template.SingleInsertBpTemplate;
import com.yonyou.pmclouds.basecom.bp.template.SingleUpdateBpTemplate;
import com.yonyou.pmclouds.basecom.consts.BillTypeConst;
import com.yonyou.pmclouds.basecom.entity.SuperVO;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.copyperson.entity.CopyPersonVO;
import com.yonyou.pmclouds.copyperson.rmiitf.ICopyPersonMaintain;
import com.yonyou.pmclouds.organization.entity.OrganizationVO;
import com.yonyou.pmclouds.organization.rmiitf.OrganizationQuery;
import com.yonyou.pmclouds.picture.entity.PictureParamVO;
import com.yonyou.pmclouds.picture.rmiitf.PictureRemoteService;
import com.yonyou.pmclouds.project.entity.ProjectVO;
import com.yonyou.pmclouds.project.processor.UpdateBillCountForDeleteProcessor;
import com.yonyou.pmclouds.project.processor.UpdateBillCountForInsertProcessor;
import com.yonyou.pmclouds.project.rmiitf.ProjectSimpleQuery;
import com.yonyou.pmclouds.repeatwork.entity.RepeatWorkVO;
import com.yonyou.pmclouds.repeatwork.mapper.RepeatWorkMapper;
import com.yonyou.pmclouds.repeatwork.process.*;
import com.yonyou.pmclouds.repeatwork.service.rmiitf.IRepeatWorkMaintain;
import com.yonyou.pmclouds.workflow.aspect.PMApprove;
import com.yonyou.pmclouds.workflow.service.rmiitf.IFlowApproveBuziService;
import jodd.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import yonyou.bpm.rest.request.AssignInfoItem;
import yonyou.bpm.rest.request.Participant;

import java.util.List;

@Service(version= ApplicationConsts.APPLICATION_VERSION, interfaceClass = IRepeatWorkMaintain.class)
public class RepeatWorkServiceImpl implements IRepeatWorkMaintain , IFlowApproveBuziService {
    private static String[] UPDATE_FIELDS ={RepeatWorkVO.REPEATDATE,RepeatWorkVO.REPEATREASON};
    private static String[] UPDATE_STATUS = {RepeatWorkVO.BILLSTATUS};

    @Autowired
    private RepeatWorkMapper mapper;
    @Autowired
    private PictureRemoteService pictureRemoteService;
    @Autowired
    private ProjectStatusCheckProcessor<RepeatWorkVO> projectStatusCheckProcessor;
    @Autowired
    private RepeatWorkLogPostProcess repeatWorkLogPostProcess;
    @Autowired
    private MobileTaskInsertProcessor<RepeatWorkVO> taskInsertProcessor;//待办
    @Autowired
    private MobileNoticeInsertProcessor<RepeatWorkVO> mobileNoticeInsertProcessor;//抄送人发通知
    @Autowired
    private RepeatWorkCopyPersonUpdateBatchProcessor repeatWorkCopyPersonUpdateBatchProcessor;  //更新抄送人
    /*@Autowired
    private BillDrivenProcessorFactory drivenProcessorFactory;*/
    @Autowired
    private UpdateBillCountForDeleteProcessor.UpdateBillCountForDeleteProcessorFactory<RepeatWorkVO> billCountDeleteFactory;
    @Autowired
    private CheckWorkStop4ProjectProcessor checkWorkStop4ProjectProcessor;
    @Autowired
    private CaculateStopDaysProcessor caculateStopDaysProcessor;
    @Autowired
    private UpdateBillCountForInsertProcessor.UpdateBillCountForInsertProcessorFactory<RepeatWorkVO> billCountFactory;  //活跃度统计
    @Autowired
    private ICopyPersonMaintain copyPersonMaintain;
    @Autowired
    private DocCenterProcessor docCenterProcessor;
    @Autowired
    private WorkRepeatNCCProcessor workRepeatNCCProcessor;
    @Autowired
    private OrganizationQuery organizationQuery;
    @Autowired
    private RepeatWorkCommitDupProcessor repeatWorkCommitDupProcessor;
    @Autowired
    private ProjectSimpleQuery projectSimpleQuery;
    @Autowired
    private RepeatWorkLocalProjectProcessor repeatWorkLocalProjectProcessor;

    @Override
    @PMApprove
    public RepeatWorkVO add(RepeatWorkVO repeatWorkVO) throws BusinessException {
        if ( repeatWorkVO == null ){
            return null;
        }
        //复工单数据持久化
        SingleInsertBpTemplate<RepeatWorkVO> bp = new SingleInsertBpTemplate<RepeatWorkVO>(mapper);
        // 更新审计信息
        bp.addBeforeProcessor(new AuditInfoInsertProcessor<RepeatWorkVO>());
        //校验必输项
        bp.addBeforeProcessor(new RepeatWorkInsertCheckProcessor());
        //防止单项目同一时段多次提交复工单。
        bp.addBeforeProcessor(repeatWorkCommitDupProcessor);
        // 复工单是基于项目未关闭的情况下
        bp.addBeforeProcessor(projectStatusCheckProcessor);
        //校验是否有相应的停工单
        bp.addBeforeProcessor(checkWorkStop4ProjectProcessor);
        //更新单据数量统计，活跃度会需要的。
        bp.addAfterProcessor(billCountFactory.getProcessor(BillTypeConst.REPEATWORK_BILLTYPE));
        //智能日志
        bp.addAfterProcessor(repeatWorkLogPostProcess);

        bp.insert(repeatWorkVO);
        //保存抄送人
        List<CopyPersonVO> copyPersonVOS =  getCopyPersonList(repeatWorkVO);
        if(copyPersonVOS != null && copyPersonVOS.size() > 0){
            copyPersonMaintain.insertBatch(copyPersonVOS);
        }
        //复工单的图片或视频保存
        PictureParamVO paramVO = new PictureParamVO(repeatWorkVO.getPkRepeatwork(),repeatWorkVO.getPkProject(), BillTypeConst.REPEATWORK_BILLTYPE);
        pictureRemoteService.insertPictureForPub(repeatWorkVO,paramVO);
        //翻译单据状态
        wrapStatus(repeatWorkVO);
        //翻译组织名称
        wrapOrgName(repeatWorkVO);
        return repeatWorkVO;
    }

    @Override
    @PMApprove(trigger = "commit")
    public RepeatWorkVO update(RepeatWorkVO repeatWorkVO) throws BusinessException {
        SingleUpdateBpTemplate<RepeatWorkVO> bp = new SingleUpdateBpTemplate<RepeatWorkVO>(mapper,UPDATE_FIELDS);
        //校验是否有相应的停工单
        bp.addBeforeProcessor(checkWorkStop4ProjectProcessor);
        // 更新审计信息
        bp.addBeforeProcessor(new AuditInfoInsertProcessor<RepeatWorkVO>());
        //校验必输项
        bp.addBeforeProcessor(new RepeatWorkInsertCheckProcessor());
        //抄送人更新维护
        bp.addAfterProcessor(repeatWorkCopyPersonUpdateBatchProcessor);
        // 复工单是基于项目未关闭，可进行业务的情况下
        bp.addBeforeProcessor(projectStatusCheckProcessor);
        //存储图片和小视频
        pictureRemoteService.updateBillPicture(repeatWorkVO,new PictureParamVO(repeatWorkVO.getPkRepeatwork(),repeatWorkVO.getPkProject(),repeatWorkVO.getBillType()));
        return bp.update(repeatWorkVO);
    }

    @Override
    public RepeatWorkVO approve(String pkRepeatwork, byte billStatus) throws BusinessException {
        if (StringUtil.isEmpty(pkRepeatwork)){
            return null;
        }
        RepeatWorkVO repeatWorkVO = mapper.getById(pkRepeatwork);
        SingleUpdateBpTemplate<RepeatWorkVO> bp= new SingleUpdateBpTemplate<RepeatWorkVO>(mapper,UPDATE_STATUS);
        repeatWorkVO.setBillstatus(billStatus);
        bp.addAfterProcessor(caculateStopDaysProcessor);
        // 给抄送人发送通知
//        bp.addAfterProcessor(mobileNoticeInsertProcessor);

        bp.addAfterProcessor(docCenterProcessor);

        ProjectVO projectVO = projectSimpleQuery.queryProject(repeatWorkVO.getPkProject());
        if (projectVO == null ||projectVO.getSrcType() == null ||"~".equals(projectVO.getSrcType())) {
            //本地项目状态处理
            bp.addAfterProcessor(repeatWorkLocalProjectProcessor);
        }else {
            //ncc更新项目驱动状态
            bp.addAfterProcessor(workRepeatNCCProcessor);
        }

        //修改复工单
        bp.update(repeatWorkVO);

        return repeatWorkVO;
    }

    @Override
    public RepeatWorkVO reject(String pkRepeatwork) throws BusinessException {
        if (StringUtil.isEmpty(pkRepeatwork)){
            return null;
        }
        RepeatWorkVO repeatWorkVO = mapper.getById(pkRepeatwork);
        SingleUpdateBpTemplate<RepeatWorkVO> bp= new SingleUpdateBpTemplate<RepeatWorkVO>(mapper,UPDATE_STATUS);
        repeatWorkVO.setBillstatus(BillStatusConst.COMMON_REJECT_STATUS);
        // 复工单是基于项目未关闭的情况下
        bp.addBeforeProcessor(projectStatusCheckProcessor);
        //单据驱动项目状态改变
//        bp.addAfterProcessor(drivenProcessorFactory.getBillDrivenProcessor(BillTypeConst.REPEATWORK_BILLTYPE, (BillDrivenProcessorFactory.AdditionalInfoToDriven<RepeatWorkVO>) null));
        // 给抄送人发送通知
//        bp.addAfterProcessor(mobileNoticeInsertProcessor);
        //修改复工单
        bp.update(repeatWorkVO);
        return repeatWorkVO;
    }

    @Override
    public SuperVO approveByPkBill(String pk_bill, byte billStatus) throws BusinessException {
        return approve(pk_bill,billStatus);
    }

    @Override
    public SuperVO rejectByPkBill(String pk_bill) throws BusinessException {
        return reject(pk_bill);
    }

    @Override
    public SuperVO queryDetailForWorkFlow(String pk_bill) throws BusinessException {
        RepeatWorkVO repeatWorkVO = mapper.getById(pk_bill);
        return repeatWorkVO;
    }

    @Override
    public String getBillType() {
        return BillTypeConst.REPEATWORK_BILLTYPE;
    }

    @Override
    public SuperVO deleteBill(SuperVO businessVO) throws BusinessException {
        SingleDeleteBpTemplate<RepeatWorkVO> deleteBpTemplate = new SingleDeleteBpTemplate<RepeatWorkVO>(mapper);
        //更新单据
        deleteBpTemplate.addAfterProcessor(billCountDeleteFactory.getProcessor(BillTypeConst.REPEATWORK_BILLTYPE));
        return deleteBpTemplate.delete((RepeatWorkVO) businessVO);
    }

    @Override
    public Object getMapper() {
        return mapper;
    }

    private List<CopyPersonVO> getCopyPersonList(RepeatWorkVO repeatWorkVO){
        List<CopyPersonVO> copyPersonVOList = repeatWorkVO.getCopyPersons();
        if(copyPersonVOList != null && copyPersonVOList.size() > 0){
            for(CopyPersonVO copyPersonVO : copyPersonVOList){
                copyPersonVO.setPkBill(repeatWorkVO.getPkRepeatwork());
            }
        }
        return copyPersonVOList;
    }

    /**
     * 状态翻译
     * @param repeatWorkVO
     */
    private void wrapStatus(RepeatWorkVO repeatWorkVO) {
        if (repeatWorkVO.getBillstatus() != null) {
            switch (repeatWorkVO.getBillstatus()) {
                case BillStatusConst.COMMON_APPROVING_STATUS:
                    repeatWorkVO.setStatus("审批中");
                    repeatWorkVO.setStrBillstatus("审批中");
                    break;
                case BillStatusConst.COMMON_REJECT_STATUS:
                    repeatWorkVO.setStatus("驳回");
                    repeatWorkVO.setStrBillstatus("驳回");
                    break;
                case BillStatusConst.COMMON_APPROVED_STATUS:
                    repeatWorkVO.setStatus("审批通过");
                    repeatWorkVO.setStrBillstatus("审批通过");
                    break;
                case BillStatusConst.COMMON_COMMIT_STATUS:
                    repeatWorkVO.setStatus("驳回后再提交");
                    repeatWorkVO.setStrBillstatus("驳回后再提交");
                    break;
                case BillStatusConst.COMMON_FREE_STATUS:
                    repeatWorkVO.setStatus("自由态");
                    repeatWorkVO.setStrBillstatus("自由态");
            }
        }
    }

    /**
     * 组织名字翻译
     * @param repeatWorkVO
     */
    private void wrapOrgName(RepeatWorkVO repeatWorkVO) throws BusinessException {
        //翻译组织名称
        String pkProject = repeatWorkVO.getPkProject();
        ProjectVO projectVO = projectSimpleQuery.queryProject(pkProject);

        if(projectVO != null){
            repeatWorkVO.setProjectName(projectVO.getSname());
            repeatWorkVO.setProjectCode(projectVO.getScode());
            //有可能存在项目组织不存在的项目档案。
            if(projectVO.getPkOrg() == null){
                return;
            }
            OrganizationVO organizationVO = organizationQuery.queryByPkSrc(RuntimeEnvironment.getTenantId(), projectVO.getPkOrg());
            if(organizationVO != null){
                repeatWorkVO.setOrgName(organizationVO.getSname());
                repeatWorkVO.setPkOrganization(organizationVO.getPkOrganization());
                repeatWorkVO.setPkOrgSrc(organizationVO.getPkSrc());
            }
        }
    }
}
